package com.util;

import com.security.CustomUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 这里负责将jwt中的用户信息转换为身份认证、权限验证用的用户信息
 */
@Component
@Slf4j
public class AuthenticationAdaptor {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    /**
     * 将jwt中的用户信息转换为Authentication，同时添加权限信息
     * @param userInfo  jwt中的用户信息
     * @return  携带权限信息的Authentication
     */
    public Authentication adapte(UserInfo userInfo) {
        // 这里需要实现权限信息获取
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(
                customUserDetailsService.listAuth(userInfo.getId()).toArray(new String[0]));
        User principal = new User(userInfo.getName(), "", authorities);
        return new UsernamePasswordAuthenticationToken(principal, "", authorities);
    }
}
